package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.user.mapper.ApUserRealNameMapper;
import com.heima.user.service.ApUserRealNameService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
@Transactional
public class ApUserRealNameServiceImpl extends ServiceImpl<ApUserRealNameMapper, ApUserRealname> implements ApUserRealNameService {

    /**
     * 分页条件查询用户认证审核列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult pageList(AuthDto dto) {
        //检查参数
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //分页
        dto.checkParam();
        IPage page = new Page(dto.getPage(),dto.getSize());

        //根据状态查询
        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus() != null){
            wrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }

        //查询返回结果
        page = page(page,wrapper);
        return new PageResponseResult(page);
    }

    /**
     * 审核用户认证
     * @param dto
     * @param uri
     * @return
     */
    @Override
    public ResponseResult auth(AuthDto dto, String uri) {
        //检查参数
        if (dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        ApUserRealname realname = getById(dto.getId());
        if (realname.getStatus() != (short) 1){
            return ResponseResult.errorResult(AppHttpCodeEnum.REALNAME_STATUS_NOTAUDIT);
        }
        //审核通过
        if (uri.endsWith("authPass")){
            realname.setStatus((short) 9);
            updateById(realname);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } else {
            //审核失败
            realname.setStatus((short) 2);
            realname.setReason(dto.getMsg());
            updateById(realname);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
    }
}
